import SparkMD5 from 'spark-md5'

// 计算MD5
export const calculateMd5 = async (file) => {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		const spark = new SparkMD5.ArrayBuffer()
		const reader = new FileReader()
		reader.readAsArrayBuffer(file.file || new Blob([file]))
		reader.onload = (e) => {
			spark.append(e.target.result)
			const md5 = spark.end()
			resolve(md5)
		}
		reader.onerror = (error) => {
			reject(new Error('文件读取失败'))
		}
		// #endif

		// #ifdef APP-PLUS
		// 确保使用正确的文件路径
		const filePath = file.path || file.url

		console.log("filePath", filePath)
		if (!filePath) {
			reject(new Error('文件路径无效'))
			return
		}

		plus.io.getFileInfo({
			filePath: filePath,
			digestAlgorithm: "md5",
			success: function(e) {
				if (e && e.digest) {
					console.log("e.digest", e.digest)
					resolve(e.digest)
				} else {
					reject(new Error('MD5计算失败'))
				}
			},
			fail: function(e) {
				console.error('获取文件信息失败：', e)
				reject(new Error('获取文件信息失败'))
			}
		})
		// #endif
	})
}